package servlets;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JOptionPane;

import beans.Usuario;


public class CadastroUsuarioServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
   
    public CadastroUsuarioServlet() {
        super();
    }

    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		
		processaCadastro(request, response);
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processaCadastro(request, response);
	}
	
	@SuppressWarnings("unchecked")
	public void processaCadastro(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
		
		request.setCharacterEncoding("UTF-8");
		
		String email = request.getParameter("email");
		String senha = request.getParameter("senha");

		Usuario usuario = new Usuario();
		usuario.setEmail(email);
		usuario.setSenha(senha);

		ArrayList<Usuario> listaDeUsuarios = null;
		boolean jaExiste = false;
		
		String path = getServletContext().getRealPath("/bancodados/login.obj");
		
		try {
			
			FileInputStream fis = new FileInputStream(path);
			ObjectInputStream ois = new ObjectInputStream(fis);
			listaDeUsuarios = (ArrayList<Usuario>) ois.readObject();
			ois.close();
			for (Usuario u : listaDeUsuarios) {
				if(u.getEmail().equals(usuario.getEmail())){
					jaExiste = true;
				}				
			}
			if(!jaExiste){
				listaDeUsuarios.add(usuario);
			}
		} catch (Exception e) {
			listaDeUsuarios = new ArrayList<Usuario>();
			listaDeUsuarios.add(usuario);
		}
		
		try{
			FileOutputStream fos = new FileOutputStream(path);
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			oos.writeObject(listaDeUsuarios);
			oos.close();
		} catch (Exception e){
			e.printStackTrace();
		}
		
				
		String url = null;
		
		if(!jaExiste){
			url = "login.jsp"; 
		}else{ 
			JOptionPane.showMessageDialog(null,"Email já cadastrado!" );
			url = "cadastrousuario.jsp"; 	
		}
		
		response.setContentType("text/html;charset=UTF-8");  
		
		RequestDispatcher dispatcher = request.getRequestDispatcher(url);
		dispatcher.forward(request, response);
	}

}
